package com.dnjn.mes.biz.assist;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dnjn.mes.biz.Const;
import com.dnjn.mes.biz.domain.*;
import com.dnjn.mes.biz.enums.ExceptStatus;
import com.dnjn.mes.biz.enums.MaintainType;
import com.dnjn.mes.biz.enums.MessageType;
import com.dnjn.mes.biz.service.*;
import com.dnjn.mes.biz.websocket.WebSocketServer;
import com.dnjn.mes.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@Component
//@Component("workforceTask")
public class WorkforceHandler {
    @Autowired
    private IMesEquipmentService equipmentService;
    @Autowired
    private IMesWorkforceConfigService workforceConfigService;
    @Autowired
    private IMesWorkforceXrefService workforceXrefService;
    @Autowired
    private IMesWorkforceShiftClockingService shiftClockingService;
    @Autowired
    private IMesWorkforceShiftService shiftService;

    @Autowired
    private IMesRecordBeatService beatService;
    @Autowired
    private IMesRecordExceptService recordExceptService;
    @Autowired
    private IMesExceptService exceptService;
    @Autowired
    private IMesMessageService messageService;

    //测试环境定时添加数据的定时器
    @Scheduled(cron = "${cron:-}")
    @Transactional
    public void insertTableDate() {
        log.error("测试环境定时添加数据的定时器已执行");
        Long equipmentId = equipmentService.fetchCurrent().getEquipmentId();
        //插入节拍表数据
        LocalDateTime localDateTime = LocalDateTime.now();
        List<MesRecordBeat> beatList = new ArrayList<>();
        for (int i = 1; i < 101; i++) {
            LocalDateTime dateTime = LocalDateTime.now().minusMinutes(i);
            MesRecordBeat beat = new MesRecordBeat();
            beat.setCurrentDatetime(dateTime);
            Random r = new Random();
            beat.setDataValue(r.nextInt(100));
            beat.setEquipmentId(equipmentId);
            beatList.add(beat);
        }
        beatService.saveBatch(beatList);
        //插入record_except表数据
        List<MesExcept> list = exceptService.list();
        LocalDateTime now = LocalDateTime.now();
        List<MesRecordExcept> recordExceptList = new ArrayList<>();
        List<MesMessage> mesMessageList = new ArrayList<>();
        for (int i = 1; i < 11; i++) {
            Random random = new Random();
            MesExcept except = list.get(random.nextInt(list.size()));
            MesRecordExcept recordExcept = new MesRecordExcept();
            recordExcept.setExceptId(except.getExceptId());
            recordExcept.setEquipmentId(equipmentId);
            recordExcept.setExceptStatus(ExceptStatus.TODO);
            recordExcept.setCreateTime(now);
            recordExcept.setStartDatetime(now);
            recordExceptList.add(recordExcept);
            MesMessage msg = new MesMessage()
                    .setMessageStatus(Const.YES)
                    .setMessageType(MessageType.WORKPIECE_EXCEPT)
                    .setMessage(except.getExceptMessage())
                    .setMessageCn(except.getExceptMessageCn())
                    .setStartDatetime(now)
                    .setEquipmentId(equipmentId)
                    .setExceptId(except.getExceptId())
                    .setWorkpieceId(null);
            mesMessageList.add(msg);
        }
        recordExceptService.saveBatch(recordExceptList);
        //插入message表数据
        messageService.saveBatch(mesMessageList);

    }


    /**
     * 定时任务 五分钟执行一次，查询班次表中时间段，当前时间在开始时间前15分钟，将班次信息写入 mes_workforce_shift 班次记录表,同步将班次下的用户列表写到 mes_workforce_shift_clocking 表
     */
//    @Scheduled(cron = "0 */5 * * * ? ")
//    @Scheduled(cron = "0/1 * * * * ? ")
    /*@Transactional
    public void handleTask() {
        MesEquipment mesEquipment = equipmentService.fetchCurrent();
        log.info("---- start workforckSchedule---------------------------------");
        QueryWrapper<MesWorkforceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", "0");
        List<MesWorkforceConfig> configList = workforceConfigService.list(queryWrapper);
        for (MesWorkforceConfig mesWorkforceConfig : configList) {
            LocalTime startTime = mesWorkforceConfig.getStartTime();
            LocalTime endTime = mesWorkforceConfig.getEndTime();
            LocalTime now = LocalTime.now();
            Boolean flag = checkTimeBeforemin(now, startTime, endTime);
            if (flag) {
                //先查询班次记录表是否有当前班次这条信息有就不新增
                LocalDate localDate = LocalDateTime.now().toLocalDate();
                Long count = shiftService.lambdaQuery().eq(MesWorkforceShift::getCurrentDate, localDate).eq(MesWorkforceShift::getWorkforceLabel, mesWorkforceConfig.getWorkforceName()).count();
                if(count > 0){
                    continue;
                }
                //写之前先将班次记录表的delete属性全部修改为1
                shiftService.updateDeleted();
                //将班次信息写入 mes_workforce_shift 班次记录表,
                MesWorkforceShift mesWorkforceShift = new MesWorkforceShift();
                mesWorkforceShift.setWorkforceId(mesWorkforceConfig.getWorkforceId());
                mesWorkforceShift.setCurrentDate(localDate);
                mesWorkforceShift.setEquipmentId(mesEquipment.getEquipmentId());
                mesWorkforceShift.setWorkforceLabel(mesWorkforceConfig.getWorkforceName());
                shiftService.save(mesWorkforceShift);

                //同步将班次下的用户列表写到 mes_workforce_shift_clocking 表
                QueryWrapper<MesWorkforceXref> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("workforce_id", mesWorkforceConfig.getWorkforceId());
                List<MesWorkforceXref> xrefList = workforceXrefService.list(queryWrapper1);
                //if (null != xrefList && xrefList.size() > 0) {
                for (MesWorkforceXref mesWorkforceXref : xrefList) {
                    //先查询 mes_workforce_shift_clocking 表是否已经存在当前用户记录
//                    String date = DateUtils.getDate();
//                    MesWorkforceShiftClocking mesWorkforceShiftClocking = shiftClockingService.checkClockUser(date, mesEquipment.getEquipmentId(), mesWorkforceXref.getUserId());
//                    if (null == mesWorkforceShiftClocking) {
                        MesWorkforceShiftClocking clocking = new MesWorkforceShiftClocking();
                        clocking.setShiftId(mesWorkforceShift.getShiftId());
                        clocking.setHasClockin("0");
                        clocking.setHasClockout("0");
                        clocking.setEquipmentId(mesEquipment.getEquipmentId());
                        clocking.setUserId(mesWorkforceXref.getUserId());
                        clocking.setUserName(mesWorkforceXref.getUserName());
                        shiftClockingService.save(clocking);
 //                   }
                }
//               }
            }
        }


    }

    //校验现在时间，是否在开始时间 前十五分钟之内  8:00   7:40  7:45
    private Boolean checkTimeBeforemin(LocalTime now, LocalTime startTime, LocalTime endTime) {
        LocalTime startTime1 = startTime.minusMinutes(15);
        if (now.isAfter(startTime1) && now.isBefore(startTime)) {
            return true;
        } else {
            return false;
        }
    }*/


}
